package com.szewec.ps.util.ossservice;

import android.content.Context;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.google.gson.JsonParser;
import com.szewec.ps.myinterface.OssServiceCallBack;
import com.szewec.ps.util.dialog.LoadingDialog;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.HashMap;

public class OssServiceUtil {
    /**
     * 初始化OSS上传对象
     */
    public static void initOssService(Context context, OssServiceCallBack callBack, LoadingDialog _loadingDialog) {
        OkHttp.get("/tpms-file-service/api/file/actions/get-oss-token", new HashMap<>(), _loadingDialog, (result -> {
            JsonParser jp = new JsonParser();
            String token = jp.parse(result).getAsJsonObject().get("data").getAsJsonObject().get("securityToken").getAsString();
            String accessKeyId = jp.parse(result).getAsJsonObject().get("data").getAsJsonObject().get("accessKeyId").getAsString();
            String accessKeySecret = jp.parse(result).getAsJsonObject().get("data").getAsJsonObject().get("accessKeySecret").getAsString();
            String endpoint = jp.parse(result).getAsJsonObject().get("data").getAsJsonObject().get("endpoint").getAsString();
            String bucketName = jp.parse(result).getAsJsonObject().get("data").getAsJsonObject().get("bucket").getAsString();
            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, token);

            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            //回调回到了主线程,重起线程
            new Thread(() -> {
                OSS oss = new OSSClient(context, endpoint, credentialProvider, conf);
                OssService ossService = new OssService(oss, bucketName);
                callBack.onSuccess(bucketName, ossService);
            }).start();
        }));

    }
}
